using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace Hsenl.Network {
    public class TcpSender : IOCPSender {
        public event Func<int, Memory<byte>> SendBufferGetter;
        public event Action<Memory<byte>> OnSendDataEvent;

        public TcpSender(AddressFamily addressFamily, SocketBufferKind bufferKind = SocketBufferKind.Memory) : base(
            new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp), bufferKind) { }

        public TcpSender(Socket socket, SocketBufferKind bufferKind = SocketBufferKind.Memory) : base(socket, bufferKind) {
        }

        protected override Memory<byte> GetSendBuffer(int length) {
            return this.SendBufferGetter!.Invoke(length);
        }

        protected override Memory<byte> GetSendToBuffer(int length, out EndPoint remoteEndPoint) {
            throw new NotImplementedException();
        }

        protected override byte[] GetSendBuffer(int length, out int offset, out int count) {
            throw new NotImplementedException();
        }

        protected override byte[] GetSendToBuffer(int length, out int offset, out int count, out EndPoint remoteEndPoint) {
            throw new NotImplementedException();
        }

        protected override void OnSend(Memory<byte> data) {
            this.OnSendDataEvent?.Invoke(data);
        }

        public bool SendAsync() {
            return base.SendAsync();
        }

        public override void Close(bool closeSocket = true) {
            if (this.IsClosed)
                return;

            base.Close(closeSocket);

            this.SendBufferGetter = null;
            this.OnSendDataEvent = null;
        }

        public override void Dispose() {
            if (this.IsDisposed)
                return;

            base.Dispose();

            this.SendBufferGetter = null;
            this.OnSendDataEvent = null;
        }
    }
}